<?php

/**
 * The basic user registration form.
 */
function hgn_user_register_form($form,&$form_state){
  
  return $form;
}


/**
 * The user profile form
 */
function hgn_user_order_form($form,&$form_state){
  
  return $form;
}


function hgn_user_order_phone_verify_form($form,&$form_state){
  global $user;
  $cus_data = hgn_core_load_cus_info($user->uid);
  if(!$cus_data['is_cus'] || $cus_data['verified']){
    drupal_set_message("You don't need to verify your phone number!'","error");
    return;
  }
  
  $form['phone_number'] = array(
    "#type" => "textfield",
    "#title"=> t("Phone Number"),
    "#size" => 10,
    "#value"=> $cus_data['contact_num'],
    "#disabled" => TRUE,
  );
  $form['verify_code'] = array(
    "#type"  => "textfield",
    "#title" => t("Verification Code"),
    "#description" => t("If you didn't get the verification code, you may ".l("resend","user/".$user->uid."/resend_code")),
    "#size"  => 5,
  );
  $form['submit'] = array(
    "#type" => "submit",
    "#value"=> t("Submit"),
  );
  return $form;
}


function hgn_user_order_phone_verify_form_validate($form,&$form_state){
  global $user;
  $res = db_select(HGNT_CONT_VERIFY,'v')->condition('duid',$user->uid)->fields('v')->orderBy('gen_time',"DESC")->execute()->fetchAssoc();
  
  if(empty($res) || $res['gen_time'] < hgn_core_get_lowest_allowed_verify_gen_time()){
    hgn_user_phone_verify_send_code($user->uid);
    form_set_error('verify_code',"Sorry your verification code has expired. System has sent you a new code.");
  } else if($res['verify_code'] != $form_state['values']['verify_code']){
    hgn_user_phone_verify_send_code($user->uid);
    form_set_error('verify_code',"Sorry your verification code is wrong, a new code has been sent to your cellphone.");
  }
}

function hgn_user_order_phone_verify_form_submit($form,&$form_state){
  global $user;
  db_update(HGNT_CUSTOMER)->fields(array('verified'=>'1'))->condition('duid',$user->uid)->execute();
  db_delete(HGNT_CONT_VERIFY)->condition('duid',$user->uid)->execute();
  // and unset the info
  $cus_data = &hgn_core_load_cus_info($user->uid); unset($cus_data);
  drupal_set_message("Verification succeeded!");
}

function hgn_user_phone_verify_send_code_page($uid){
  $cus_data = hgn_core_load_cus_info($uid);
  if(!$cus_data['verified']){
    hgn_user_phone_verify_send_code($uid);
    drupal_set_message("TODO: generate verify code and send via SMS","error");
  } else{
    drupal_set_message("Sorry You Don't need to verify your phone number");
  }
  return "";
}

function hgn_user_phone_verify_send_code($uid){
  $code = sprintf("%04d",rand(0,9999));
  $record_to_write = array(
    'duid'  => $uid,
    'verify_code' => $code,
    'gen_time'  => time(),
  );
  drupal_write_record(HGNT_CONT_VERIFY, $record_to_write);
  // TODO: generate verify code and send via SMS
}

function hgn_core_get_lowest_allowed_verify_gen_time(){
  return time() - 10000;  // TODO: just a stub function here.
}
